package cn.samler.diandi.api.service.impl;

import cn.samler.diandi.api.entity.Eval;
import cn.samler.diandi.api.entity.Rank;
import cn.samler.diandi.api.entity.User;
import cn.samler.diandi.api.mapper.UserRankMapper;
import cn.samler.diandi.api.model.db.UserRankCalcResult;
import cn.samler.diandi.api.model.io.Response;
import cn.samler.diandi.api.service.UserRankService;
import cn.samler.diandi.api.utils.ContextHolderUtil;
import cn.samler.diandi.api.utils.ResponseBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRankServiceImpl implements UserRankService {
    UserRankMapper userRankMapper;

    public UserRankServiceImpl(UserRankMapper userRankMapper) {
        this.userRankMapper = userRankMapper;
    }

    /**
     * 获取用户的评分均值
     *
     * @param uid user id
     * @return Response
     */
    @Override
    public Response getRankByUserId(Integer uid) {
        if(uid <= 0) {
            User user = (User) ContextHolderUtil.getCurrentUser();
            uid = user.getId();
        }
        List<Rank> result = userRankMapper.getRankByUserId(uid);

        return new ResponseBuilder().success().msg("获取成功").data(result).build();
    }

    /**
     * 计算并更新用户的最新评分均值
     *
     * @param eval user eval实体
     */
    @Override
    @Async
    public void update(Eval eval) {
        UserRankCalcResult result = userRankMapper.calc(eval.getId(), eval.getRole());
        userRankMapper.update(result);
    }
}
